package per.jdz.retryer.proxy;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import per.jdz.retryer.core.Retryer;

public class RetryerProxy implements MethodInterceptor {
    private Object target;

    private Map<Integer, Retryer> retryerMap;

    public RetryerProxy() {
    }

    public RetryerProxy(Object target, Map<Integer, Retryer> retryerMap) {
        this.target = target;
        this.retryerMap = retryerMap;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        final int hashCode = method.hashCode();
        if (retryerMap.containsKey(hashCode)) {
            return retryerMap.get(hashCode).exec(() -> {
                final Object o1;
                try {
                    o1 = methodProxy.invokeSuper(obj, args);
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }
                return o1;
            });
        }
        return methodProxy.invokeSuper(obj, args);
    }

}